package com.charles.seckillfile.controller;

import com.charles.seckillapi.model.SysFile;
import com.charles.seckillcommon.core.domain.R;
import com.charles.seckillfile.service.FileUploadService;
import com.charles.seckillfile.utils.FileHandlerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
public class FileController {
    
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    
    @Resource
    private FileUploadService fileUploadService;
    
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file) {
        try
        {
            // 上传并返回访问地址
            String url = fileUploadService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileHandlerUtils.getName(url));
            sysFile.setUrl(url);
            return R.success(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
    
}
